﻿using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using YiSha.Admin.Web.Controllers;
using YiSha.Basics;
using YiSha.CodeGenerator.Model;
using YiSha.CodeGenerator.Template;
using YiSha.Framework;
using YiSha.Model.Result;
using YiSha.Model.Result.SystemManage;
using YiSha.Service;
using YiSha.Service.IService;
using YiSha.Service.SystemManage;
using YiSha.Util;
using YiSha.Util.Model;

namespace YiSha.Admin.Web.Areas.ToolManage.Controllers
{
    [Area("ToolManage")]
    public class CodeGeneratorController : BaseController
    {
        public DatabaseTableService DatabaseTableService { get; set; }
        #region  构造函数
        /// <summary>
        /// 数据库表信息
        /// </summary>
        private IDatabaseTableService databaseTableService;
        /// <summary>
        /// 数据库表信息
        /// </summary>
        public CodeGeneratorController()
        {
            string dbType = GlobalContext.SystemConfig.DBProvider;
            switch (dbType)
            {
                case "SqlServer":
                    databaseTableService = new DatabaseTableSqlServerService();
                    break;
                case "MySql":
                    databaseTableService = new DatabaseTableMySqlService();
                    break;
                case "Oracle":
                    databaseTableService = new DatabaseTableOracleService();
                    break;
                default:
                    throw new Exception("未找到数据库配置");
            }
        }
        #endregion
        #region 视图功能
        [AuthorizeFilter("tool:codegenerator:view")]
        public IActionResult CodeGeneratorIndex()
        {
            return View();
        }

        public IActionResult CodeGeneratorForm(string outputModule)
        {
            ViewBag.OutputModule = outputModule;
            return View();
        }

        public IActionResult CodeGeneratorEditSearch()
        {
            return View();
        }

        public IActionResult CodeGeneratorEditToolbar()
        {
            return View();
        }

        public IActionResult CodeGeneratorEditList()
        {
            return View();
        }

        #endregion

        #region 获取数据
        [HttpGet]
        [AuthorizeFilter("tool:codegenerator:search")]
        public async Task<IActionResult> GetTableFieldTreeListJson(string tableName)
        {
            TData<List<ZtreeInfo>> obj = await DatabaseTableService.GetTableFieldZtreeList(tableName);
            return Json(obj);
        }
        /// <summary>
        /// 查询表信息
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="upper"></param>
        /// <returns></returns>
        [HttpGet]
        [AuthorizeFilter("tool:codegenerator:search")]
        public async Task<IActionResult> GetTableFieldTreePartListJson(string tableName, int upper = 0)
        {
            TData<List<ZtreeInfo>> obj = await DatabaseTableService.GetTableFieldZtreeList(tableName);
            if (obj.Data != null)
            {
                // 基础字段不显示出来
                obj.Data.RemoveAll(p => BaseField.BaseFieldList.Contains(p.name));
            }
            return Json(obj);
        }

        [HttpGet]
        [AuthorizeFilter("tool:codegenerator:search")]
        public async Task<IActionResult> GetBaseConfigJson(string tableName)
        {
            TData<BaseConfigModel> obj = new TData<BaseConfigModel>();

            string tableDescription = string.Empty;
            //
            TData<List<TableFieldInfo>> tDataTableField = await DatabaseTableService.GetTableFieldList(tableName);
            List<string> columnList = tDataTableField.Data.Where(p => !BaseField.BaseFieldList.Contains(p.TableColumn)).Select(p => p.TableColumn).ToList();

            OperatorInfo operatorInfo = await OperatorService.Instance.Current();
            //获取项目路径
            string serverPath = GlobalContext.HostingEnvironment.ContentRootPath;
            obj.Data = new NewSingleTableTemplate().GetBaseConfig(serverPath, operatorInfo.UserName, tableName, tableDescription, columnList);
            return Json(obj);
        }
        #endregion

        #region 提交数据
        [HttpPost]
        [AuthorizeFilter("tool:codegenerator:add")]
        public async Task<IActionResult> CodePreviewJson(BaseConfigModel baseConfig)
        {
            TData<object> obj = new TData<object>();
            //if (string.IsNullOrEmpty(baseConfig.OutputConfig.OutputModule))
            //{
            //    obj.Msg = "请选择输出到的模块";
            //}
            //else
            //{
            NewSingleTableTemplate template = new NewSingleTableTemplate();
            //获取数据库表字段
            TData<List<TableFieldInfo>> objTable = await DatabaseTableService.GetTableFieldList(baseConfig.TableName);
            DataTable dt = DataTableHelper.ListToDataTable(objTable.Data);  // 用DataTable类型，避免依赖
            string codeEntity = template.BuildEntity(baseConfig, dt);
            string codeEntityParam = template.BuildEntityParam(baseConfig, objTable.Data);
            string codeService = template.BuildService(baseConfig, dt, objTable.Data);
            // string codeBusiness = template.BuildBusiness(baseConfig);
            string codeController = template.BuildController(baseConfig);
            string codeIndex = template.BuildIndex(baseConfig, objTable.Data);
            string codeForm = template.BuildForm(baseConfig, objTable.Data);
            string codeMenu = template.BuildMenu(baseConfig);

            var json = new
            {
                CodeEntity = HttpUtility.HtmlEncode(codeEntity),
                CodeEntityParam = HttpUtility.HtmlEncode(codeEntityParam),
                CodeService = HttpUtility.HtmlEncode(codeService),
                // CodeBusiness = HttpUtility.HtmlEncode(codeBusiness),
                CodeController = HttpUtility.HtmlEncode(codeController),
                CodeIndex = HttpUtility.HtmlEncode(codeIndex),
                CodeForm = HttpUtility.HtmlEncode(codeForm),
                CodeMenu = HttpUtility.HtmlEncode(codeMenu)
            };
            obj.Data = json;
            //}
            return Json(obj);
        }

        [HttpPost]
        [AuthorizeFilter("tool:codegenerator:add")]
        public async Task<IActionResult> CodeGenerateJson(BaseConfigModel baseConfig, string Code)
        {
            TData<List<KeyValue>> obj = new TData<List<KeyValue>>();
            if (!GlobalContext.SystemConfig.Debug)
            {
                obj.Msg = "请在本地开发模式时使用代码生成";
            }
            else
            {
                NewSingleTableTemplate template = new NewSingleTableTemplate();
                //获取数据库表信息
                var tableField = databaseTableService.GetTableList(baseConfig.TableName).Result;
                List<KeyValue> result = await template.CreateCode(baseConfig, HttpUtility.UrlDecode(Code), tableField.Data);
                obj.Data = result;
            }
            return Json(obj);
        }
        #endregion
    }
}